package com.yuanxiao.task;

import com.yuanxiao.pojo.Order;
import com.yuanxiao.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Component
public class OrderTask implements ApplicationListener<ApplicationStartedEvent> {
    @Autowired
    OrderService orderService;
    @Value("${order.mq.message.ttl}")
    private String orderMqMessageTtl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private String redisKey = "order_remaining";
    private String notPayRedisKey = "order_notpay";
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        executor.scheduleAtFixedRate(() -> {
                    List<Order> unPayOrders = orderService.getUnPayOrders(10);for (Order order : unPayOrders) {
                        if (order.getStatus().equals("未付款")) {
                            Date orderTime = order.getOrderTime();
                            Instant orderTimeInstant = orderTime.toInstant();
                            Instant now = Instant.now();
                            if (Duration.between(orderTimeInstant, now).getSeconds() * 1000 > Long.parseLong(orderMqMessageTtl)) {
                                System.out.println("订单" + order.getId() + "过期未支付");
                                orderService.updateOrderStatusById(order.getId(), "已取消", "超时未支付");
                                redisTemplate.opsForValue().increment(redisKey, 1);
                                redisTemplate.opsForValue().decrement(notPayRedisKey, 1);
                            }
                        }
                    }


                },
                10L, 5, TimeUnit.SECONDS);

    }
}
